#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BUF 8
char buf[MAX_BUF]="hello\n";
int main(void)
{
	int hf;
	int bytesWritten;
	int bytesRead;
	int offset = 0;
    int offsettmp = 0;
	//char *pbuf = buf;
	int i = 0;
	char ch;
    struct flock lock;
    printf("%d\n",O_ACCMODE);
	hf = open("testfile.txt", O_RDWR|O_CREAT|O_TRUNC, S_IRWXU);
	if(-1 == hf)
	{
		printf("failed to open file\n");
		return 1;
	}
	if(offset = lseek(hf, 0, SEEK_SET) == -1)
		return 1;
	else
		printf("offset=%d\n", offset);

	
    lock.l_type = F_WRLCK;
    lock.l_whence = SEEK_SET;
    lock.l_start = 0;
    lock.l_len = 0;

    if((fcntl(hf, F_SETLK, &lock)) < 0)
    {
        perror("fcntl WR lock error"); 
        return -1;
    }
    else
    {
        printf("fcntl WR lock success\n");
    	bytesWritten = write(hf, buf, sizeof(buf)/sizeof(char));
	    if(-1 == bytesWritten)
		    return 1;
	    else
		    printf("succeed to write %d chars to file\n", bytesWritten);
	    printf("%s\n",buf);
        
        ch = getchar();

        lock.l_type = F_UNLCK;
        if((fcntl(hf, F_SETLK, &lock)) < 0)
        {
            perror("fcntl WR unlock error"); 
            return -1;
        }
        else
            printf("fcntl WR unlock success\n");
 
    getchar();
    }
	memset(buf, 0, MAX_BUF);
    lock.l_type = F_RDLCK;
    if((fcntl(hf, F_SETLK, &lock)) < 0)
    {
        perror("fcntl RD lock error"); 
        return -1;
    }
    else
        printf("fcntl RD lock success\n");


/*
	if(offset = lseek(hf, 0, SEEK_SET) == -1)//write函数移动了文件指针，读的时候必须让它指向文件开头
		return 1;
	else
		printf("offset=%d\n", offset);
*/
	if(offsettmp = lseek(hf, 0, SEEK_END) == -1)//write函数移动了文件指针，读的时候必须让它指向文件开头
		return 1;
	else
		printf("offsettmp=%d\n", offsettmp);
    bytesRead = read(hf, buf, sizeof(buf)/sizeof(char));
	if(-1 == bytesRead)
		return 1;
	else
		printf("succeed to read %d chars from file\n", bytesRead);

    getchar();
    lock.l_type = F_UNLCK;
    if((fcntl(hf, F_SETLK, &lock)) < 0)
    {
        perror("fcntl RD unlock error"); 
        return -1;
    }
    else
        printf("fcntl RD unlock success\n");

    getchar();
	printf("output the chars now.......\n");
	printf("%s\n",buf);
	
	close(hf);

}
